#!/usr/bin/env python3

import gt
import random
import os

#  全局变量定义处
#  H = gt.h() - 1
#  W = gt.w() - 1
H = 10
W = 30
color = 31
y = 3
x = 3
x_inc = 1
y_inc = 1

def show_bg():  # 定位背景位置
    print("\033[1;1H", end='', flush=True)
    # 背景定位开始位置 #不换行 #刷新画布
    for r in range(H):
        for c in range(W):
            ch = '#' if r == 0 or c == 0 or r == H - 1 or c == W - 1 else ' '
                    # 打印边框
            print(ch, end='', flush=True)
        print(flush=True)

def ball_init(): # 初始化
    print("\033[2J\033[?25l", end='', flush=True)
        # 清屏、清除光标
    gt.init()
    gt.run(move, 0.001)


def ball_exit(): # 还原操作
    print("\033[?25h\033[%d;1H" % (H + 2), flush=True)
        # 还原光标、定位下两行
    gt.exit()
    os._exit(0)


def move():
    global x, y, H, W, x_inc, y_inc

    #  H = gt.h() - 1
    #  W = gt.w() - 1

    show_bg()

    print("\033[%d;%dH\033[%dm@\033[0m" % (y, x, color), end='', flush=True)
        # @的坐标
    if x == 1 or x == W:
        x_inc *= -1
        # x坐标反向
    if y == 1 or y == H:
        y_inc *= -1
        # y坐标反向
    x += x_inc
    y += y_inc

    gt.run(move, 0.1)


def ball_run():
    global direct, color, x_inc, y_inc

    while True:
        ch = gt.get()
        if ch == 'q':
            break
        elif ch == 'w':
            y_inc = -1
        elif ch == 's':
            y_inc = 1
        elif ch == 'a':
            x_inc = -1
        elif ch == 'd':
            x_inc = 1
        elif ch == ' ':
            color = random.randint(30, 37)

def ball_main():
    ball_init()

    ball_run()

    ball_exit()


ball_main()
